package com.self.cloudmall.pms.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.self.cloudmall.common.enumm.AttrTypeEnum;
import com.self.cloudmall.pms.entity.AttrAttrgroupRelationEntity;
import com.self.cloudmall.pms.entity.AttrGroupEntity;
import com.self.cloudmall.pms.entity.CategoryEntity;
import com.self.cloudmall.pms.service.AttrAttrgroupRelationService;
import com.self.cloudmall.pms.service.AttrGroupService;
import com.self.cloudmall.pms.service.CategoryService;
import com.self.cloudmall.pms.utils.PageUtils;
import com.self.cloudmall.pms.utils.Query;
import com.self.cloudmall.pms.vo.AttrVo;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import com.self.cloudmall.pms.mapper.AttrMapper;
import com.self.cloudmall.pms.entity.AttrEntity;
import com.self.cloudmall.pms.service.AttrService;
import org.springframework.transaction.annotation.Transactional;


@Service("attrService")
public class AttrServiceImpl extends ServiceImpl<AttrMapper, AttrEntity> implements AttrService {
    
    @Autowired
    private AttrAttrgroupRelationService attrAttrgroupRelationService;
    @Autowired
    private AttrGroupService attrGroupService;
    @Autowired
    private CategoryService categoryService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<AttrEntity> page = this.page(
                new Query<AttrEntity>().getPage(params),
                new QueryWrapper<AttrEntity>()
        );

        return new PageUtils(page);
    }


    @Transactional(rollbackFor = Exception.class)
    @Override
    public boolean saveAttr(AttrVo attrVo) {
        AttrEntity attr = new AttrEntity();
        BeanUtils.copyProperties(attrVo,attr);
        this.save(attr);
        if (attrVo.getAttrType() != null && AttrTypeEnum.ATTR_TYPE_BASE.getCode() == attrVo.getAttrType()){
            if (attrVo.getAttrGroupId() != null){
                AttrAttrgroupRelationEntity relationEntity = new AttrAttrgroupRelationEntity();
                relationEntity.setAttrId(attr.getAttrId());
                relationEntity.setAttrGroupId(attrVo.getAttrGroupId());
                attrAttrgroupRelationService.save(relationEntity);
            }
        }
        return true;
    }

    @Override
    public PageUtils queryPageByCatelogId(Map<String, Object> params, Long catelogId,String type) {
        QueryWrapper<AttrEntity> queryWrapper = new QueryWrapper<>();
        LambdaQueryWrapper<AttrEntity> lambda = queryWrapper.lambda();
        String key = (String) params.get("key");
        if (StringUtils.isNotEmpty(key)){
            lambda.eq(AttrEntity::getAttrId,key).or().like(AttrEntity::getAttrName,key);
        }
        if (catelogId != null && catelogId != 0){
            lambda.eq(AttrEntity::getCatelogId,catelogId);
        }
        if (AttrTypeEnum.ATTR_TYPE_BASE.getType().equalsIgnoreCase(type)){
            lambda.eq(AttrEntity::getAttrType,AttrTypeEnum.ATTR_TYPE_BASE.getCode());
        }else{
            lambda.eq(AttrEntity::getAttrType,AttrTypeEnum.ATTR_TYPE_SALE.getCode());
        }
        IPage<AttrEntity> page = this.page(
                new Query<AttrEntity>().getPage(params),
                queryWrapper
        );
        PageUtils pageUtils = new PageUtils(page);

        List<AttrEntity> records = page.getRecords();
        List<AttrVo> collect = records.stream().map(x -> {
            AttrVo vo = new AttrVo();
            BeanUtils.copyProperties(x, vo);
            CategoryEntity categoryEntity = categoryService.getById(x.getCatelogId());
            if (categoryEntity != null){
                vo.setCatelogName(categoryEntity.getName());
            }
            //销售属性，不需要关联属性组的
            if (AttrTypeEnum.ATTR_TYPE_BASE.getType().equalsIgnoreCase(type) &&  x.getAttrId() != null){
                AttrAttrgroupRelationEntity relationEntity = attrAttrgroupRelationService.lambdaQuery()
                        .eq(AttrAttrgroupRelationEntity::getAttrId, x.getAttrId())
                        .one();
                if (relationEntity != null && relationEntity.getAttrGroupId() != null) {
                    AttrGroupEntity groupEntity = attrGroupService.getById(relationEntity.getAttrGroupId());
                    if (groupEntity != null) {
                        vo.setGroupName(groupEntity.getAttrGroupName());
                    }
                }
            }
            return vo;
        }).collect(Collectors.toList());

        pageUtils.setList(collect);

        return pageUtils;
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public boolean updateAttrEntity(AttrVo attrVo) {
        AttrEntity attr = new AttrEntity();
        BeanUtils.copyProperties(attrVo,attr);
        this.updateById(attr);
        if (attrVo.getAttrType() != null && AttrTypeEnum.ATTR_TYPE_BASE.getCode() == attrVo.getAttrType()
         && attrVo.getAttrGroupId() != null){
            Integer count = attrAttrgroupRelationService.lambdaQuery().eq(AttrAttrgroupRelationEntity::getAttrId,attrVo.getAttrId())
                    .count();
            AttrAttrgroupRelationEntity relationEntity = new AttrAttrgroupRelationEntity();
            relationEntity.setAttrGroupId(attrVo.getAttrGroupId());
            relationEntity.setAttrId(attrVo.getAttrId());
            if (count != null && count > 0){
                attrAttrgroupRelationService.lambdaUpdate().eq(AttrAttrgroupRelationEntity::getAttrId,attrVo.getAttrId())
                .update(relationEntity);
            }else{
                attrAttrgroupRelationService.save(relationEntity);
            }
        }

        return true;
    }

    @Override
    public AttrVo getAttrVoById(Long attrId) {
        AttrEntity attrEntity = this.getById(attrId);
        AttrVo vo = new AttrVo();
        BeanUtils.copyProperties(attrEntity,vo);
        if (attrEntity.getAttrType() != null && AttrTypeEnum.ATTR_TYPE_BASE.getCode() == attrEntity.getAttrType()){
            AttrAttrgroupRelationEntity relationEntity = attrAttrgroupRelationService.lambdaQuery()
                    .eq(AttrAttrgroupRelationEntity::getAttrId, attrEntity.getAttrId())
                    .one();
            if (relationEntity != null){
                vo.setAttrGroupId(relationEntity.getAttrGroupId());
            }
        }
        vo.setCatelogPath(attrGroupService.findCatelogPath(attrEntity.getCatelogId()));
        return vo;
    }

}